<!-- 奖金优化 -->
<template>
  <div class='bonusOptimize'>
    <!-- 头部 -->
    <Header :title="`${isBaskt ? '篮球' : '足球'}奖金优化`" />
    <!-- <MyHeader class="head" :title="`${isBaskt?'篮球':'足球'}奖金优化`" @onClickRight="goToInstructions">
      <template #right>
        <i class='iconfont question'>&#xe653;</i>
      </template>
    </MyHeader> -->
    <!-- 金额输入框 -->
    <div class='input'>
      <span>输入金额：</span>
      <div>
        <input type="text" v-model="price" @blur="inputBetAmount()">
        <b>元</b>
      </div>
    </div>
    <!-- 优化方式选择 -->
    <div class='tabBar-box'>
      <div :class="{'active': type===item.id}" @click="toggleType(item.id)" v-for="(item, index) in optimizationTypes"
        :key="index">
        <p>
          <span>{{item.name}} <i v-show='type==item.id' class='iconfont'>&#xe627;</i></span>
        </p>
      </div>
    </div>
    <!-- 详情展示 表头 -->
    <div class='tip'>
      <div class='left'>选项</div>
      <div class='center'>注数</div>
      <div class='right'>理论奖金</div>
    </div>
    <!-- 详情展示 表体 -->
    <div class='box'>
      <div class='pox' v-for='(optimize) in combinedChuan' :key='optimize.index'>
        <div class='cont'>
          <div class='left' @click='openScheme(optimize.index)'>
            <p v-for="(item, i) in optimize.text" :key="i">
              {{transWeek(item[2]) +' '+ item[0]}}
              <span>{{ `[${item[1]} ${item[4]}]` }}</span>
            </p>
            <p :id='"i" + optimize.index'><van-icon name='arrow-down'></van-icon></p>
          </div>
          <van-stepper v-model="zsObj[optimize.index]" integer :min="1" @minus="addBonus(-1, optimize.index)"
            @plus="addBonus(1, optimize.index)" @blur="zsChangeHandle(optimize.index)" />
          <div class='right'>
            <span>{{ Number(optimize.money.toFixed(2)) }}元</span>
          </div>
        </div>
        <!-- 投注方案 -->
        <div class='bettingScheme' :id='"s" + optimize.index'>
          <div class='tit'>投注方案</div>
          <table>
            <thead>
              <tr>
                <th>场次</th>
                <th>主队</th>
                <th v-if="!isBaskt">让</th>
                <th>客队</th>
                <th>投注</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for='(item, index3) in optimize.text' :key='index3'>
                <td>{{ transWeek(item[2]) }}</td>
                <td>{{ item[0] }}</td>
                <td v-if="!isBaskt">{{ item[5] }}</td>
                <td>{{ item[6] }}</td>
                <td>{{ `${item[1]}[${item[4]}]` }}</td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
    <!-- 详情展示 表尾 -->
    <!-- <div class='tip'>
      <div class='left'>合计</div>
      <div class='center'>{{result.length}}</div>
    </div> -->
    <!-- 底部按钮 -->
    <footer>
      <p>因赔率随时变动，请与终端机赔率核对，最终结果以出票为准！</p>
      <div>
        <div class='model'>
          <!-- <p>过关：{{'aaaa'}}</p> -->
          <p>理论奖金：{{totalInfo.min}} ～ {{totalInfo.max}} 元</p>
          <p>投注：<span>{{totalInfo.ZhuShu}}</span>注<span>{{totalInfo.ZhuShu * 2}}</span>元</p>
        </div>
        <div class='btn'>确认</div>
      </div>
    </footer>
  </div>
</template>

<script setup>
import { storeToRefs } from 'pinia'
import { useCalcStore } from "@/stores";
import { useRouter } from 'vue-router'
import optimize from '@/utils/optimize.js'

const router = useRouter()
const calc = useCalcStore() // 竞猜store
const { betAmount, times, isInShares } = storeToRefs(calc)

const type = ref(1)
const price = ref(0)
const isBaskt = ref(false)
const combinedChuan = shallowRef()
const zsObj = ref({}); // 注数的映射对象
const totalInfo = reactive({
  ZhuShu: 0,
  min: 0,
  max: 0,
})
let opt, possibleComb;

price.value = betAmount.value * Number(times.value)
calc.changeBetAmount(price.value)

const optimizationTypes = [
  { id: 1, name: '平均优化' },
  { id: 2, name: '博热保本' },
  { id: 3, name: '博冷保本' }
]

onBeforeMount(()=>{
  var optData = JSON.parse(sessionStorage.getItem('optData'));
  possibleComb = JSON.parse(sessionStorage.getItem('possibleComb'));
  opt = new optimize(optData);
  opt.doAvg();
  price.value = opt.minMoney;
  isBaskt.value = optData.lottery && optData.lottery =='basketball';
  updateTotalInfo();
})

const toggleType = (type1) => {
  if(type1!==1){
    const name = type1==2?'博热':'博冷'
    // 博冷博热不支持组合过关和复合过关
    if(opt.ggMaps.length>1) return Toast(`${name}优化暂不支持复合过关！`);
    if(opt.ggMaps[0]!=opt.data.changshu) return Toast(`${name}优化暂不支持组合过关！`);
    opt.doHot(type1===2 ? 'hot' : 'cold');
  }else{
    opt.doAvg();
  }
  type.value = type1;
  updateTotalInfo();
  // const optype = optimizationTypes.value[type1 - 1]
  // if (modelInfos.value[0].issingle) {
  //   // 增加单关玩法后，当所选的串关方式为单关，只能进行平均优化
  //   if(type1 === 2 || type1 === 3){
  //     Toast(`${optype.name}暂不支持组合过关！`)
  //   }
  // } else {
  //   // 判断是否合理
  //   if(!reasonable.value) {
  //     if(type1 === 2 || type1 === 3){
  //       Toast(`${optype.name}暂不支持组合过关！`)
  //     }
  //   } else {
  //     type.value = type1
  //     // optimizationType()
  //     reckon({type:type.value})
  //   }
  // }
}

const inputBetAmount = () => {
  // 判断输入数字
    if(!price.value) return Toast('优化金额不能为空') // 判断非空
    else if(isNaN(price.value)) return Toast('请输入数字') // 判断非空
    else if(Number(price.value) < opt.minMoney) return Toast('请输入1倍以上方案金额进行优化') // 优化金额不能小于最小金额
    else if(Number(price.value) > 100000) return Toast('购买金额请不要超过10万元！') // 输入金额不能超10万
    else if(Number(price.value) % 2 !== 0) return Toast('请输入大于0的偶数金额再进行优化！') // 输入金额不能超10万
    // 不能是奇数
    else{
      calc.changeBetAmount(price.value)
      reComputer2()
    }
}
const goToInstructions = () =>{
  if (isInShares.value) {
    router.push({path: '/gMatchAnalyze/bonusCalculator/instructions'})
  } else {
    router.push({path: '/bonusCalculator/raceColor/instructions'})
  }
}
// 展开投注方案 动画  传递当前 方案的 id名
const openScheme = (id) => {
  const body = document.getElementById('s' + id)
  let height = body.getBoundingClientRect().height
  const elementI = document.getElementById('i'+ id)
  if (height) {
    body.style.height = height + 'px'
    // const f = document.body.offsetHeight
    body.style.height = '0px'
    // 旋转箭头
    elementI.style.transform = 'rotate(0)'
  } else {
    body.style.height = 'auto'
    height = body.getBoundingClientRect().height
    body.style.height = '0'
    // var f = document.body.offsetHeight
    body.style.height = height + 'px'
    // 旋转箭头
    elementI.style.transform = 'rotate(180deg)'
  }
}
// 增加或者减少优化注数
function addBonus(num, index) {
  opt.doAdd(num, index);
  updateTotalInfo(true);
  // combinedChuan.value[index].num++
  // let sum = 1
  // combinedChuan.value[index].matchData.forEach((item) => {
  //   sum *= item.match(regex)[1]
  // })
  // combinedChuan.value[index].showPrice = (sum * combinedChuan.value[index].num * 2).toFixed(2)
  // state.result.betNumber++
}

function zsChangeHandle(index){
  var obj = opt.listOrder.find(item=>item.index==index);
  if(obj){
    const diffVal = zsObj.value[index] - obj.zhushu;
    opt.doAdd(diffVal, index);
    updateTotalInfo(true);
  }
}

// 重新计算每个组合的订单数
function reComputer2(){
  opt.data.money = Number(price.value);
  if(type.value!==1){
    opt.doAvg();
    opt.doHot(type.value===2 ? 'hot' : 'cold');
  }else{
    opt.doAvg();
  }
  updateTotalInfo();
}

function updateTotalInfo(isAdd=true){
  combinedChuan.value = opt.listOrder;
  for (const item of combinedChuan.value){
    zsObj.value[item.index] = item.zhushu
  }
  totalInfo.ZhuShu = eval(opt.zhushu.join("+"));
  totalInfo.min = Number(Math.min.apply(null, opt.moneys).toFixed(2));
  if(!isAdd){
    totalInfo.max = eval(opt.maxMoneys.join("+")).toFixed(2);
  }else{
    const maxMoneyArr = [];
    for(let pos of possibleComb){
      let maxMoney = 0;
      for(let comp of opt.listOrder){
        const arr = comp.text.map(item=>`${item[2]}@${item[3]}@${item[1]}`);
        // 匹配上的累加金额
        if(arr.every(element => pos.includes(element))){
          maxMoney += comp.money;
        }
      }
      // 计算每种可能性的总奖金
      maxMoneyArr.push(maxMoney);
    }
    // 从 maxMoneyArr 中取出最大值
    totalInfo.max = Number(Math.max.apply(null, maxMoneyArr).toFixed(2));
  }
  triggerRef(combinedChuan);
  // console.log(333, opt);
}
function transWeek(matchCode) {
  const weekNo = matchCode.charAt(0);
  const code = matchCode.slice(1);
  const table = {
    '1': '一',
    '2': '二',
    '3': '三',
    '4': '四',
    '5': '五',
    '6': '六',
    '7': '日',
  }
  return `周${table[weekNo]} ${code}`
}
</script>

<style lang='less' scoped>
.bonusOptimize{
  width:100%;
  height:100%;
  .head{
    i.question{
      color:#fe0000;
      font-size:.38rem;
    }
  }
  .input{
    height:1rem;
    width:100%;
    display: flex;
    align-items: center;
    justify-content: center;
    span{
      font-size:.32rem;
      color:#333;
    }
    div{
      width:2.42rem;
      height:30px;
      padding:0 .1rem;
      border:1px solid #fe0000;
      display: flex;
      align-items: center;
      justify-content: space-between;
      input{
        width: 1.75rem;
        height:100%;
        border:0;
        background: #eee;
        color:#fe0000;
        font-size: 14px;
      }
      b{
        font-weight: normal;
        color:#999;
        font-size: 14px;
      }
    }
  }
  .tabBar-box{
    height:.8rem;
    background: #fff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom:1px solid #eee;
    div{
      width:50%;
      height:100%;
      // padding: 10px 0;
      display: flex;
      justify-content: center;
      align-items: center;
      position: relative;
      p{
        width:100%;
        height:.42rem;
        display:flex;
        justify-content: center;
        align-items: center;
        border-right:1px solid #eee;
        // line-height: .8rem;
        span{
          font-size:.3rem;
          color:#999;
          i{
            font-size:.24rem;
            position: absolute;
            bottom:0rem;
            left:50%;
            transform: translateX(-50%);
          }
        }
      }
    }
    div:last-of-type{
      p{
        border-right:0;
      }
    }
    .active{
      span{
        color:#fe0000;
      }
    }
  }
  .tip{
    width:100%;
    height:32px;
    border-bottom: 1px solid #eee;
    padding: 0 .2rem;
    display: flex;
    background: #fff;
    position: relative;
    div{
      height:100%;
      line-height: 32px;
      font-size:.3rem;
      color:#000;
    }
    .left{
      width:3.54rem;
      padding-left:1.18rem;
    }
    .center{
      position: static;
      transform: none;
      left:0;
      top:0;
      width:1.82rem;
      text-align: center;
    }
    .right{
      width:1.8rem;
      text-align: right;
    }
  }
  .box{
    position: absolute;
    top:3.32rem;
    left:0;
    right:0;
    bottom:80px;
    overflow: scroll;
    //  解决 iso 滑动卡顿问题
    -webkit-overflow-scrolling : touch;
    .pox{
      background: #fff;
      width:100%;
      padding: 0 .2rem;
    }
    .cont{
      padding: 10px 0;
      display: flex;
      border-bottom:1px solid #eee;
      position: relative;
      >div{
        display: flex;
        align-items: center;
        justify-content: center;
      }
      .left{
        width:3.54rem;
        flex-direction: column;
        align-items: flex-start;
        div{
          width:auto;
          height:100%;
          position: relative;
        }
        p {
          font-size: .26rem;
          color: #333;
          span {
            color: #0182cd;
          }
        }
        p:last-of-type {
          width: 90%;
          transition: .3s;
          text-align: center;
          line-height: .2rem;
          // transform: rotate(180deg);
        }
        i {
          font-size: .3rem;
        }
      }
      .center{
        position: static;
        transform: none;
        left:0;
        top:0;
        width:1.82rem;
        >div{
          width:100%;
          height:30px;
          display: flex;
          border-radius: 5px;
          border:1px solid #999;
          justify-content: space-between;
          align-items: center;
          padding: 0 .05rem;
        }
        p{
          width:.55rem;
          height:100%;
          text-align: center;
          font-size:.4rem;
          color:#fe0000;
          font-weight: 550;
          &:last-child{
            line-height: 30px;
          }
        }
        span{
          font-size:.32rem;
          color:#333;
        }
      }
      .right{
        width:1.8rem;
        justify-content: flex-end;
        span{
          color:#fe0000;
          font-size:14px;
        }
      }
    }
    .bettingScheme{
      width:7.5rem;
      margin-left:-10px;
      background: #ccecff;
      height:0;
      transition: height .3s;
      overflow: hidden;
      .tit{
        width:100%;
        height:.7rem;
        line-height: .7rem;
        font-size:.3rem;
        color:#000;
        border-bottom:1px solid #fff;
        text-align: center;
      }
      table{
        width:100%;
        padding-bottom: 10px;
        th{
          border-bottom: 1px solid #fff;
          height:.58rem;
          font-size:.3rem;
        }
        td{
          text-align: center;
          font-size:14px;
        }
        td:last-of-type{
          color:#3192d4;
        }
      }
    }
  }
  footer{
    position: fixed;
    left:0;
    bottom:0;
    padding: .2rem;
    width: 100%;
    height: 1.5rem;
    background: #fff;
    >p{
      font-size: 11px;
      color: #f00;
    }
    >div{
      display: flex;
      justify-content: space-between;
      align-items: center;
      .model{
        p{
          font-size:.3rem;
          color:#000;
          span{
            color:#fe0000;
            margin:0 2.5px;
            font-size:.32rem;
          }
          span:first-of-type{
            margin-left:0;
          }
        }
      }
      .btn{
        width:2.04rem;
        height:.82rem;
        background: #fe0000;
        color:#fff;
        text-align: center;
        line-height: .82rem;
        border-radius: 4px;
        font-size:17px;
      }
    }
  }
}
</style>
